package com.oa.android.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oa.android.R;
import com.oa.android.adapter.FujAdapter;
import com.oa.android.entry.Fjian;
import com.oa.android.utils.ImageUtlis;
import com.oa.android.utils.UConstants;
import com.oa.android.utils.Util;
import com.oa.android.view.MyGridView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;


/**
 * Created by zouqh on 2017-01-01.
 */

public class EditAllActivity extends Activity implements View.OnClickListener{


    @InjectView(R.id.close)
    ImageView close;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.ritgh_icon)
    ImageView ritghIcon;
    @InjectView(R.id.ritgh_text)
    TextView ritghText;
    @InjectView(R.id.Title)
    EditText Title;
    @InjectView(R.id.fuj)
    TextView fuj;
    @InjectView(R.id.content)
    EditText content;
    @InjectView(R.id.addFile)
    TextView addFile;

    private String tpye;
    private String strTitle;
    private String strContent;
    private String id;
    private ProgressDialog progressDialog;
    private Dialog Jdialog;
    private List<File> listFile;
    private MyGridView listFj;
    private FujAdapter adapter;
    List<Fjian> list;
    private int num;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_all_activity);
        listFj=(MyGridView)findViewById(R.id.listFj);
        ButterKnife.inject(this);
        tpye=getIntent().getStringExtra("type");
        strTitle=getIntent().getStringExtra("title");
        strContent=getIntent().getStringExtra("content");
        id=getIntent().getStringExtra("id");
        listFile = new ArrayList<>();
//        if (tpye.equals("1")){
            titleText.setText("编辑公告");
//        }else if (tpye.equals("2")){
//            titleText.setText("编辑邮件");
//        }
        getFj();
        ritghText.setVisibility(View.VISIBLE);
        ritghText.setText("保存");
        Title.setText(strTitle);
        content.setText(strContent);
        ritghText.setOnClickListener(this);
        close.setOnClickListener(this);
        addFile.setOnClickListener(this);
        fuj.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (fuj.getText().length()>0){
                    pointDialog("确定清除附件吗？");
                }

                return false;
            }
        });

        listFj.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("listFj---",position+"---");
                if (Util.NoNull(list.get(position).getXH())){
                    deleteFujian(position);
                }else{
                    list.remove(position);
                    listFile.remove(position-num);
                    adapter.notifyDataSetChanged();
                }

                return false;
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.close:
                finish();
                break;

            case R.id.ritgh_text:
                strTitle=Title.getText().toString();
                strContent=content.getText().toString();
                if (!Util.NoNull(strTitle)){
                    Toast.makeText(this,"标题不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!Util.NoNull(strContent)){
                    Toast.makeText(this,"内容不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                progressDialog = ProgressDialog.show(this, null, "加载中...", true, false);
                if (listFile.size()>0){
                    upFj();
                }else{
                    getChange();
                }

                break;
            case R.id.addFile:
               Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 1);
                break;


        }
    }
    /**
     * 提示
     */
    private void pointDialog(String str) {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.exti_dialog,
                null);
        // 对话框
        Jdialog = new Dialog(this);
        Jdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Jdialog.show();

        Jdialog.setContentView(layout);
        TextView sure = (TextView) layout.findViewById(R.id.sureExti);
        TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
        TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);
        dialogTitle.setText(str);
        sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//				ContextUtil.getInstance().finishApp();
                Jdialog.cancel();
                fuj.setText("");
                listFile.clear();


            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Jdialog.dismiss();
            }
        });

    }


    //修改内容
    public void getChange() {
        Util.printLog("------------UConstants.GET_ID-----", UConstants.EDIT_GG);

        RequestParams params = new RequestParams(UConstants.EDIT_GG);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("EmpId", UConstants.EmpId);
        params.addBodyParameter("TITLE", strTitle);
        params.addBodyParameter("CONTENT", strContent);
        params.addBodyParameter("ID", id);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
//						String msg = object.getString("msg");
                        progressDialog.dismiss();
                        if (success) {
                            Toast.makeText(x.app(), "修改成功！", Toast.LENGTH_LONG).show();
                            DetailsGGaoActivity.activity.setViewUI(strTitle,strContent);
                            finish();
                        } else {
                            Toast.makeText(x.app(), "修改失败！", Toast.LENGTH_LONG).show();

                        }
//
                    } catch (JSONException e) {
                        progressDialog.dismiss();
                        Toast.makeText(x.app(), "修改失败！", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "修改失败！", Toast.LENGTH_LONG).show();
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                progressDialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Uri mPhotoUri = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {//是否选择，没选择就不会继续

            if (requestCode==1){
                Uri uri = data.getData();
                String  path= ImageUtlis.getRealPathFromUri(this,uri);
                if (null==path||path.length()<=0){
                    Toast.makeText(this,"获取文件失败",Toast.LENGTH_SHORT).show();
                    return;
                }
                File file = new File(path);
                listFile.add(file);
                String s = fuj.getText().toString();
                if (s.length() > 0) {
                    fuj.setText(s + "|" + file.getName());
                } else {
                    fuj.setText(file.getName());
                }
                Fjian fjian=new Fjian();
                fjian.setOLDNAME(file.getName());
                list.add(fjian);
                adapter.notifyDataSetChanged();
                System.out.println("img_path===" +path);
            }

//
        }
    }



    //上传附件
    public void upFj() {

        RequestParams params = new RequestParams(UConstants.UP_FILI);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("TNAME", "ERPGGTZ");
        params.addBodyParameter("XH",id );
        Util.printLog("UConstants.UP_FILI------------onSuccess-----", UConstants.UP_FILI);
        for (int i=0;i<listFile.size();i++){
            params.addBodyParameter("FILE",listFile.get(i));
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");

//                        String msg = object.getString("msg");
                        if (success) {
                           getChange();
                        } else {
                            isShow();
                            Toast.makeText(x.app(), "附件上传失败！", Toast.LENGTH_LONG).show();
                        }
//
                    } catch (JSONException e) {
                        isShow();
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(),  "附件上传出错！", Toast.LENGTH_LONG).show();
                isShow();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                isShow();
            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void isShow(){
        if (null!=progressDialog&&progressDialog.isShowing()){
            progressDialog.dismiss();
        }
    }


    //获取附件
    public void getFj() {
        Util.printLog("------------UConstants.GET_ID-----", UConstants.GET_ID);
        progressDialog = ProgressDialog.show(this, null, "加载中...", true, false);
        RequestParams params = new RequestParams(UConstants.GET_FJLIST);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("TNAME", "ERPGGTZ");
        params.addBodyParameter("XH", id);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
//						String msg = object.getString("msg");
                        if (success) {
                            Gson gson = new Gson();
                            Type lt = new TypeToken<List<Fjian>>() {
                            }.getType();
                            list = gson.fromJson(object.getString("rows").toString(), lt);
                            if (list != null && list.size() > 0) {
                                num=list.size();
                                adapter=new FujAdapter(EditAllActivity.this,list);
                                listFj.setAdapter(adapter);
                            }else{
                                list=new ArrayList<Fjian>();
                                adapter=new FujAdapter(EditAllActivity.this,list);
                                listFj.setAdapter(adapter);
                            }


                        } else {
                            list=new ArrayList<Fjian>();
                            adapter=new FujAdapter(EditAllActivity.this,list);
                            listFj.setAdapter(adapter);
                            Toast.makeText(x.app(), "获取附件失败！", Toast.LENGTH_LONG).show();

                        }
//
                    } catch (JSONException e) {
                        list=new ArrayList<Fjian>();
                        adapter=new FujAdapter(EditAllActivity.this,list);
                        listFj.setAdapter(adapter);
                        Toast.makeText(x.app(), "获取附件失败！", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }
                progressDialog.dismiss();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");
                list=new ArrayList<Fjian>();
                adapter=new FujAdapter(EditAllActivity.this,list);
                listFj.setAdapter(adapter);
                Toast.makeText(x.app(), "获取附件失败！", Toast.LENGTH_LONG).show();
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                progressDialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }



    //删除附件
    private void deleteFujian(final int positon) {
        progressDialog = ProgressDialog.show(this, null, "删除中...", true, false);
        RequestParams params = new RequestParams(UConstants.DELETE_FUJ);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("ID", list.get(positon).getID());
        params.addBodyParameter("TANME", list.get(positon).getTNAME());

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);

                        boolean success = object.getBoolean("success");
//
                        if (success) {
                            num--;
                            list.remove(positon);
                            adapter.notifyDataSetChanged();

                        } else {
                            Toast.makeText(x.app(), "删除失败！", Toast.LENGTH_LONG).show();
                        }
//
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                progressDialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "删除失败！", Toast.LENGTH_LONG).show();
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                progressDialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }
}